package com.xb.system.service.impl;

import com.google.common.hash.BloomFilter;
import com.xb.model.domain.*;
import com.xb.system.config.CSVDataConfig;
import com.xb.system.config.TxtDataV1Config;
import com.xb.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author wjh
 * @create 2024-07-23 17:01
 */
@Service
@Slf4j
public class DynamicDataSplitterServiceImpl implements DynamicDataSplitterService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private UsersInfoService usersInfoService;

    @Autowired
    private UsersInfoV1Service usersInfoV1Service;

    @Autowired
    private CSVDataConfig csvDataConfig;
    @Autowired
    private TxtDataV1Config txtDataV1Config;

    @Resource
    private DistinctUsersInfoService distinctUsersInfoService;

    @Resource
    private DistinctUsersInfoV1Service distinctUsersInfoV1Service;


    public UsersInfo processLine(String[] parts,
                                 BloomFilter<String> businessEmailBloomFilter) {

        if (parts.length < 26) { // 确保有足够的列
            return null;
        }

        UserInfoData userInfoData = new UserInfoData();

        // 遍历字段并处理
        for (int index : csvDataConfig.getIndexes()) {
            if (index < parts.length) {
                userInfoData.setFieldByIndex(index, parts[index]);
            }
        }

        if (!businessEmailBloomFilter.mightContain(userInfoData.getBusinessEmail())) {
            // 如果 Bloom Filter 中没有此邮箱，插入到 users_info
            UsersInfo userInfo = new UsersInfo(null, userInfoData.getFirstName(), userInfoData.getLastName(), userInfoData.getBusinessEmail(), userInfoData.getPersonalEmails(),
                    userInfoData.getJobTitle(), userInfoData.getSeniorityLevel(), userInfoData.getDepartment(), userInfoData.getMobilePhone(), userInfoData.getLinkedinUrl(),
                    userInfoData.getContactMetroCity(), userInfoData.getContactState(), userInfoData.getCompanyName(), userInfoData.getCompanyDomain(),
                    userInfoData.getCompanyPhone(), userInfoData.getPrimaryIndustry(), userInfoData.getPrimarySic(), userInfoData.getCompanyIndustry(),
                    userInfoData.getCompanySicCode(), userInfoData.getCompanyAddress(), userInfoData.getCompanyCity(), userInfoData.getCompanyState(),
                    userInfoData.getCompanyZip(), userInfoData.getCompanyLinkedinUrl(), userInfoData.getCompanyRevenue(), userInfoData.getCompanyEmployeeCount(),
                    userInfoData.getBusinessEmailValidationStatus());
            businessEmailBloomFilter.put(userInfoData.getBusinessEmail());
            return userInfo; // 确保在用户插入成功的情况下返回
        } else {
            // 检查并插入到 distinct_users_info
            distinctUsersInfoService.save(new DistinctUsersInfo(null, userInfoData.getFirstName(), userInfoData.getLastName(), userInfoData.getBusinessEmail(), userInfoData.getPersonalEmails(),
                    userInfoData.getJobTitle(), userInfoData.getSeniorityLevel(), userInfoData.getDepartment(), userInfoData.getMobilePhone(), userInfoData.getLinkedinUrl(),
                    userInfoData.getContactMetroCity(), userInfoData.getContactState(), userInfoData.getCompanyName(), userInfoData.getCompanyDomain(),
                    userInfoData.getCompanyPhone(), userInfoData.getPrimaryIndustry(), userInfoData.getPrimarySic(), userInfoData.getCompanyIndustry(),
                    userInfoData.getCompanySicCode(), userInfoData.getCompanyAddress(), userInfoData.getCompanyCity(), userInfoData.getCompanyState(),
                    userInfoData.getCompanyZip(), userInfoData.getCompanyLinkedinUrl(), userInfoData.getCompanyRevenue(), userInfoData.getCompanyEmployeeCount(),
                    userInfoData.getBusinessEmailValidationStatus())); // 填充相应的参数
            return null;
        }
    }

    public UsersInfoV1 processLine(String line) {
        String[] parts = line.split("\\s+");  // 按空白字符分割数据
        return processParts(parts);
    }
    public UsersInfoV1 processParts(String parts[]) {

        if (parts.length < 26) { // 确保有足够的列
            return null;
        }

        UserInfoV1Data userInfoV1Data = new UserInfoV1Data();

        // 遍历字段并处理
        for (int index : txtDataV1Config.getIndexes()) {
            if (index < parts.length) {
                userInfoV1Data.setFieldByIndex(index, parts[index]);
            }
        }

        if (true) {
            // 如果 Bloom Filter 中没有此邮箱，插入到 users_info
            UsersInfoV1 usersInfoV1 = new UsersInfoV1(null, userInfoV1Data.getFirstName(), userInfoV1Data.getLastName());
//            businessEmailBloomFilter.put(userInfoData.getBusinessEmail());
            return usersInfoV1; // 确保在用户插入成功的情况下返回
        } else {
            distinctUsersInfoV1Service.save(new DistinctUsersInfoV1(null,
                    userInfoV1Data.getFirstName(),
                    userInfoV1Data.getLastName()));
            return null;
        }

    }


    @Override
    public void splitData(String file) throws IOException {
        String handlerBeanName = determineHandlerBeanName(file);
        // 通过 Spring 的依赖注入获取对应的处理器类
        FileHandler fileHandler = getFileHandler(handlerBeanName);
        if (fileHandler == null) {
            throw new IllegalStateException("未找到处理程序的bean: " + handlerBeanName);
        }

        // 调用处理器类的方法处理文件
        fileHandler.handleFile(file);
    }

    private String determineHandlerBeanName(String contentType) {
        String handlerBeanName;
        String fileExtension = contentType.substring(contentType.lastIndexOf(".") + 1);
        switch (fileExtension.toLowerCase()) {
            case "txt":
                handlerBeanName = "txtFileHandler";
                break;
            case "csv":
                handlerBeanName = "CSVDocumentHandler";
                break;
            default:
                throw new IllegalArgumentException("不支持的文件类型:" + fileExtension);
        }
        return handlerBeanName;
    }


    // 根据 handlerBeanName 获取 FileHandler bean
    private FileHandler getFileHandler(String handlerBeanName) {
        return applicationContext.getBean(handlerBeanName, FileHandler.class);
    }

    // TODO 去重的逻辑提前到解析后的下一步
    public void saveBatch(List<UsersInfo> batch) {
        usersInfoService.saveBatch(batch);
        batch.clear();
    }

    public void saveTxtBatch(List<UsersInfoV1> batch) {
        usersInfoV1Service.saveBatch(batch);
        batch.clear();
    }

}
